import React, { useState } from 'react'
import { Button, Form, Input, Toast } from 'antd-mobile'
import { useSetState } from '../web/util'
import { IRegisterData, register } from '../apis/register'
import { useNavigate } from 'react-router-dom'

export const RegisterPage: React.FC<{}> = ({ }) => {
    const { data: state, setData: setState } = useSetState<IRegisterData>({ username: ``, password: ``, repassword: `` })
    const [loading, setLoading] = useState<boolean>(false)
    const navigate = useNavigate()
    const doRegister = async (data: IRegisterData) => {
        try {
            setLoading(true)
            await register(data)
            Toast.show(`恭喜您注册成功`)
            navigate(`/autojs/core/mobile/login`, { replace: true })
        } catch (e) {
            Toast.show(e.message)
        } finally {
            setLoading(false)
        }
    }
    return <div className='flex flex-col h-full px-12px'>
        <Form layout='horizontal' hasFeedback={true} className='mt-24px' onFinish={e => {
            doRegister(e)
        }} footer={<Button loading={loading} block type='submit' color='primary' size='middle'>立即注册</Button>}>
            <div className='text-center text-24px mt-18px font-600'>欢迎使用老哥助手</div>
            <p className='text-center text-14px mt-8px mb-24px'>多谢您信任老哥！</p>
            <Form.Item
                name='username'
                label='用户名'
                rules={[{ required: true, message: '用户名不能为空' }]}
            >
                <Input onChange={e => {
                    setState({
                        username: e
                    })
                }} placeholder='请输入用户名' />
            </Form.Item>
            <Form.Item
                name='password'
                label='密码'
                rules={[{ required: true, message: '密码不能为空' }]}
            >
                <Input type='password' onChange={e => {
                    setState({
                        password: e
                    })
                }} placeholder='请输入密码' />
            </Form.Item>
            <Form.Item
                name='repassword'
                label='确认密码'
                rules={[{ required: true, message: '确认密码不能为空' }]}
            >
                <Input type='password' onChange={e => {
                    setState({
                        repassword: e
                    })
                }} placeholder='请输入确认密码' />
            </Form.Item>
            <div style={{ display: 'none' }}>{(state as any)?.__time}</div>
        </Form>
    </div>
}
